home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9324 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: casbah.acns.nwu.edu!muzaffar
  2. From: muzaffar@casbah.acns.nwu.edu (Usman Muzaffar)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: problem passing a string
  5. Date: 9 Mar 1996 12:55:36 GMT
  6. Organization: Northwestern University, Evanston IL
  7. Message-ID: <4hrv48$huo@news.acns.nwu.edu>
  8. References: <4hrtsp$4mf@mulgave.octacon.co.uk>
  9. NNTP-Posting-Host: casbah.acns.nwu.edu
  10.  
  11. In article <4hrtsp$4mf@mulgave.octacon.co.uk>,
  12. Nik Palmer <Nik.Palmer@onyx.octacon.co.uk> wrote:
  13. >Hi,  Im using a textoutput routine in the fastgraph package of the
  14. >form below
  15. >    void fg_print(char *string,int n);
  16. >The string that I want to pass is initialised as below
  17. >
  18. >char string[6]
  19. >double variable= 1.2345
  20. >sprintf(string1,"%5f",variable)
  21. >
  22. >fg_print(string1,5)
  23. >
  24. >problem is it's outputting garbage, I know that string1 is only a
  25. >pointer to the memory that holds the string, and that if I want to
  26. >access the string I need string1[num].  So I think it's just
  27. >outputting 5 bytes of memory from the memory location string1.
  28. >
  29. >How do I  pass this routine the string??
  30. >Thanks for your help.
  31. >Nik
  32.  
  33. I'll bet anything that "char string[6] " is declared locally
  34. inside some function. The problem is that the pointer you pass
  35. refers to memory that fg_print can't access. It's a valid string
  36. pointer, alright, but not in a valid location.
  37.  
  38. Remember, only globals & data on the heap (stuff made by malloc and calloc, for
  39. example) is truly accessible all the time. Anything declared inside
  40. a function (including main()) is NOT valid outside that function.
  41.  
  42. Your solution is to make sure "char string[6]" is declared externally
  43. to all procedures. That is, put it at the top of your program.
  44.  
  45. -usman
  46.  
  47.  
  48.  
  49.  
  50.  
  51.